import { createRouter, createWebHistory } from 'vue-router';
import { generateDynamicRoutes } from './dynamicRoutes.js'
import {useAuthStore} from "../stores/authStore.js";
// 导入页面组件 (使用路由懒加载)
const Main = () => import('../views/Main.vue');
const BaseSlide =()=>import('@/components/Slide/BaseSlide.vue');
const Control = () => import('../views/Control.vue');
const Data = () => import('../views/Data.vue');
const Setting = () => import('../views/Setting.vue');
const User = () => import('../views/User.vue');
const NotFound = () => import('../views/NotFound.vue');
const Login=()=>import('../views/user/Login.vue');
const List = () => import('../views/user/List.vue');
// 定义路由规则
const routes = [
    {

        path: '/',
        name: 'Main',
        component: Main,
        redirect: '/dashboard',
        meta: {
            requiresAuth: true // 路由元信息示例
        },
        children : [
            {
                path: '/dashboard',
                name: 'Dashboard',
                component: Control,
                meta: {
                    title: '控制台',
                    icon: 'dashboard',
                    alwaysShow: true
                },
                children: [
                    {
                        path: '/index',
                        name: 'DashboardIndex',
                        component: Control,
                        meta: {
                            title: '首页',
                            icon: 'home'
                        }
                    }
                ]
            }
        ],

    },
    {
        path: '/login',
        name: 'Login',
        component: Login
    },
    {
        path: '/register',
        name: 'Register',
        component: () => import('../views/user/Register.vue') // 假设放在 views/user 目录下
    },
    {
        path: '/phonelogin',
        name: 'Phonelogin',
        component: () => import('../views/user/Phonelogin.vue'),
    }
]
// 创建路由器实例
const router = createRouter({
// 使用 HTML5 历史模式
    history: createWebHistory(),
// 路由规则
    routes,
// 滚动行为
    scrollBehavior(to, from, savedPosition) {
        if (savedPosition) {
            return savedPosition;
        } else {
            return { top: 0 };
        }
    }
});
// 全局前置守卫
router.beforeEach((to, from, next) => {
    console.log('路由跳转前触发')
    const requiresAuth = to.matched.some(record => record.meta?.requiresAuth);
   /* const isAuthenticated = localStorage.getItem('authToken'); // 假设你使用 localStorage 来存储 token*/
    const AuthStore = useAuthStore();
    //判断用户是否已经加载动态路由
    if(AuthStore.isAuthenticated&&!AuthStore.hasLoadedDynamicRoutes){
        addRoutes(AuthStore.menuList);
        AuthStore.hasLoadedDynamicRoutes = true
        return next({path: to.fullPath, replace: true})
    }
    if (requiresAuth && !AuthStore.isAuthenticated) {
        next('/login'); // 未登录，重定向到登录页
    } else {
        next(); // 已登录，继续导航
    }
})

// 动态添加路由
export function addRoutes(menuList) {
    const newRoutes = generateDynamicRoutes(menuList);
   newRoutes.forEach(route => {
        router.addRoute('Main', route);
    })

    console.log('newRoutes',router.getRoutes())

   // 添加404路由（必须在动态路由后添加）
    router.addRoute('Main',{
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        component: () => import('@/views/NotFound.vue')
    });
}

export default router;